package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersConfirmDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.dto.OrdersCancelDTO;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrderAdminMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.result.PageResult;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderAdminService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Service
public class OrderAdminServiceImpl implements OrderAdminService {
    @Autowired
    OrderAdminMapper orderAdminMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    WeChatPayUtil weChatPayUtil;
    @Autowired
    OrderMapper orderMapper;

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<Orders> page = orderAdminMapper.pageQuery(ordersPageQueryDTO);

        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = page.getResult().stream().map(orders -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            //根据订单详情表查菜品
            List<OrderDetail> orderDetailList = orderDetailMapper.findDishs(orders.getId());

            // 将每一条订单菜品信息拼接为字符串
            List<String> orderDishList = orderDetailList.stream().map(fishName -> {
                String orderDish = fishName.getName() + "*" + fishName.getNumber() + ";";
                return orderDish;
            }).collect(Collectors.toList());

            // 将该订单对应的所有菜品信息拼接在一起
            String s = String.join("", orderDishList);

            orderVO.setOrderDishes(s);

            return orderVO;
        }).collect(Collectors.toList());


        return new PageResult(page.getTotal(), orderVOList);
    }


    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        //根据id查询订单
        Orders orders = orderAdminMapper.findById(ordersCancelDTO.getId());
        //如果支付需要退款
        if (orders.getPayStatus() == Orders.PAID){
            weChatPayUtil.refund(
                    orders.getNumber(),
                    orders.getNumber(),
                    new BigDecimal("0.01"),
                    new BigDecimal("0.01"));
        }
        Orders orders1 = Orders.builder()
                //id
                .id(orders.getId())
                //原因
                .cancelReason(ordersCancelDTO.getCancelReason())
                //时间
                .cancelTime(LocalDateTime.now())
                //状态
                .status(Orders.CANCELLED)
                .build();
        orderAdminMapper.update(orders1);

    }
    /**
     * 拒单
     * @param ordersCancelDTO
     */
    @Override
    public void refuseOrder(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setPayStatus(Orders.REFUND);
        orders.setRejectionReason(ordersCancelDTO.getCancelReason());
        orderAdminMapper.refuseOrder(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    public void giveOrder(Long id) {
        //根据订单id查询地址
        //判断是否为下单状态，如果已经付款，则开始派送
        Orders order = orderAdminMapper.findById(id);
//            //修改订单状态
        order.setStatus(Orders.DELIVERY_IN_PROGRESS);
        //刷新订单状态
        orderMapper.update(order);
        //开始派送

       /* } else if (order.getPayStatus().equals(Orders.REFUND)) {
            throw  new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        } else {
            throw  new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }*/
    }
    /**
     * 完成订单
     * @param id
     */

    @Override
    public void complete(Long id) {
        Orders ordersDB = orderAdminMapper.findOrderByUserId(id);

        if (!ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
       /* Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());*/
        System.out.println(ordersDB);
        ordersDB.setStatus(Orders.COMPLETED);
        ordersDB.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(ordersDB);
    }



    @Override
    public void update(OrdersConfirmDTO ordersConfirmDTO) {
        Orders build = Orders.builder().id(ordersConfirmDTO.getId()).status(Orders.CONFIRMED).build();
        orderAdminMapper.update(build);
    }
    @Override
    public OrderStatisticsVO statistics() {

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();

        //查询订单的状态
        Integer orders2 = orderAdminMapper.findStatus(Orders.TO_BE_CONFIRMED);
        Integer orders3 = orderAdminMapper.findStatus(Orders.CONFIRMED);
        Integer orders4 = orderAdminMapper.findStatus(Orders.DELIVERY_IN_PROGRESS);

        //将订单状态存入OrderStatisticsVO中
        orderStatisticsVO.setToBeConfirmed(orders2);
        orderStatisticsVO.setConfirmed(orders3);
        orderStatisticsVO.setDeliveryInProgress(orders4);

        return orderStatisticsVO;
    }

    @Override
    public OrderVO details(Long id) {
        //通过订单表去查询订单明细表
        Orders orders = orderAdminMapper.findById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        List<OrderDetail> list = orderDetailMapper.findDishs(id);
        //添加上订单明细表的数据
        orderVO.setOrderDetailList(list);
        StringBuilder orderDishes = new StringBuilder();
        //遍历获取集合里每条数据
        list.forEach(new Consumer<OrderDetail>() {
            @Override
            public void accept(OrderDetail orderDetail) {
                //拼接字符串
                orderDishes.append(orderDetail.getName()+",");
            }
        });
        //添加订单菜品详情
        orderVO.setOrderDishes(orderDishes.toString());
        return orderVO;
    }


}

